package com.himore.api.web.controller.modules;

import java.util.*;

import com.himore.api.common.annotation.Log;
import com.himore.api.common.core.controller.BaseController;
import com.himore.api.common.core.domain.AjaxResult;
import com.himore.api.common.core.domain.entity.SysUser;
import com.himore.api.common.core.page.TableDataInfo;
import com.himore.api.common.enums.BusinessType;
import com.himore.api.common.utils.CommonUtils;
import com.himore.api.common.utils.DateUtils;
import com.himore.api.common.utils.ErrorCodeUtil;
import com.himore.api.common.utils.SecurityUtils;
import com.himore.api.common.utils.poi.ExcelUtil;
import com.himore.api.system.service.ISysUserService;
import com.himore.api.web.enums.AwardsTypeEnum;
import com.himore.api.web.enums.TaskIdEnum;
import com.himore.api.web.model.TSelectedAwards;
import com.himore.api.web.model.TSysAwards;
import com.himore.api.web.model.TSysGifts;
import com.himore.api.web.model.TTaskCompleteInfo;
import com.himore.api.web.service.ITSelectedAwardsService;
import com.himore.api.web.service.ITSysAwardsService;
import com.himore.api.web.service.ITTaskCompleteInfoService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


/**
 * 奖品信息Controller
 * 
 * @author ruoyi
 * @date 2021-01-14
 */
@RestController
@RequestMapping("/system/awards")
public class TSysAwardsController extends BaseController
{
    @Autowired
    private ITSelectedAwardsService tSelectedAwardsService;

    @Autowired
    private ITSysAwardsService tSysAwardsService;
    @Autowired
    private ISysUserService userService;


    @Autowired
    private ITTaskCompleteInfoService tTaskCompleteInfoService;
    /**
     * 查询奖品信息列表
     */
    @GetMapping("/list")
    public AjaxResult list(TSysAwards tSysAwards){
        startPage();

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysUser currentUser = userService.selectUserById(sysUser.getUserId());

        List<TSysAwards> list = tSysAwardsService.selectTSysAwardsList(tSysAwards);
        HashMap result = new HashMap();
        result.put("list",list);
        result.put("luckdraw",currentUser.getDrawCount());
        return AjaxResult.success(result);
    }

    /**
     * 导出奖品信息列表
     */
    @Log(title = "奖品信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSysAwards tSysAwards){
        List<TSysAwards> list = tSysAwardsService.selectTSysAwardsList(tSysAwards);
        ExcelUtil<TSysAwards> util = new ExcelUtil<TSysAwards>(TSysAwards.class);
        return util.exportExcel(list, "awards");
    }

    /**
     * 获取奖品信息详细信息
     */
    @GetMapping(value = "/{awardId}")
    public AjaxResult getInfo(@PathVariable("awardId") Long awardId){
        return AjaxResult.success(tSysAwardsService.selectTSysAwardsById(awardId));
    }

    /**
     * 新增奖品信息
     */
    @Log(title = "奖品信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSysAwards tSysAwards){
        return toAjax(tSysAwardsService.insertTSysAwards(tSysAwards));
    }

    /**
     * 修改奖品信息
     */
    @Log(title = "奖品信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSysAwards tSysAwards){
        return toAjax(tSysAwardsService.updateTSysAwards(tSysAwards));
    }

    /**
     * 删除奖品信息
     */
    @Log(title = "奖品信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{awardIds}")
    public AjaxResult remove(@PathVariable Long[] awardIds){
        return toAjax(tSysAwardsService.deleteTSysAwardsByIds(awardIds));
    }

    @GetMapping("/getAwardsInfo")
    public AjaxResult luckyDraw() {
        boolean isComplete =false;
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysUser currentUser =userService.selectUserById(sysUser.getUserId());
        int score = currentUser.getScore();
        if(score < 50){
            return AjaxResult.error(ErrorCodeUtil.E_229,"您的积分不足，不能抽奖！");
        }
        //抽奖
        TSysAwards prize =rowRewards();
        int scores = 0;
        if(null!= prize.getAwardId()){
            //判断一周内的第一次抽奖是否已经完成
            TTaskCompleteInfo tTaskCompleteInfo = new TTaskCompleteInfo();
            tTaskCompleteInfo.setTaskId(TaskIdEnum.TASK_6.getValue());
            tTaskCompleteInfo.setUserId(sysUser.getUserId());

            Map<String, Date> params = CommonUtils.getWeekDate();
            Date signBeginDate = params.get("mondayDate");
            Date signEndDate = params.get("sundayDate");
            signEndDate = DateUtils.addTimeTodate(signEndDate,1);
            tTaskCompleteInfo.setSigndateBegin(DateUtils.getYYYYMMDDDate(signBeginDate));
            tTaskCompleteInfo.setSigndateEnd(DateUtils.getYYYYMMDDDate(signEndDate));
            if(!tTaskCompleteInfoService.checkIfTaskComplete(tTaskCompleteInfo)){
                TTaskCompleteInfo completeInfo = new TTaskCompleteInfo();
                completeInfo.setUserId(sysUser.getUserId());
                completeInfo.setTaskId(TaskIdEnum.TASK_6.getValue());
                completeInfo.setCreateTime(DateUtils.getNowDate());
                tTaskCompleteInfoService.insertTTaskCompleteInfo(completeInfo);
                isComplete=true;
            }
            if("1".equals(prize.getAwardType())){
                scores = prize.getAmount();
            }
            //抽奖后  如果 不是 谢谢惠顾  就在我的奖品中生成一条数据
            TSelectedAwards tSelectedAwards = new TSelectedAwards();
            tSelectedAwards.setAwardId(prize.getAwardId());
            tSelectedAwards.setAwardName(prize.getAwardName());
            tSelectedAwards.setAmount(prize.getAmount());
            tSelectedAwards.setUserId(sysUser.getUserId());
            tSelectedAwards.setAwardType(AwardsTypeEnum.ROTARY_TABLE.getValue());
            tSelectedAwardsService.insertTSelectedAwards(tSelectedAwards);
        }
        //个人积分需要减去消费的积分
        SysUser user = new SysUser();
        user.setUserId(sysUser.getUserId());
        user.setScore(scores-50);
        userService.updateScoreOrDrawInfo(user);
        AjaxResult jsonResult=AjaxResult.success();

        jsonResult.put("awardId",prize.getAwardId());
        jsonResult.put("awardName",prize.getAwardName());
        jsonResult.put("isComplete",isComplete);

        return jsonResult;
    }

    private  TSysAwards   rowRewards(){
        //定义中奖率分母百分之
        int  probabilityCount=100;

        //最小概率
        String min="min";

        //最大概率
        String max="max";
        Double tempInt=0.0;

        //待中将商品数组
        Map<Long, Map<String,Double>> prizeMap=new HashMap<>();

        //获取商品列表
        List<TSysAwards> prizeList=tSysAwardsService.selectTSysAwardsList(new TSysAwards());

        for(TSysAwards prize:prizeList) {
            Map<String, Double> oddMap=new HashMap<>();
            //最小概率值
            oddMap.put(min, prize.getScaleMin());
            //最大概率
            oddMap.put(max, prize.getScaleMax());
            prizeMap.put(prize.getAwardId(), oddMap);//(奖品id，最小概率~最大概率)
        }
        //随机一个数字
        Double index=(Double) (Math.random()* probabilityCount)+0.1;
        TSysAwards prize=null;//中奖商品容器
        Set<Long> prizeIds=prizeMap.keySet();//拿到所有奖品id
        for(Long prizesId:prizeIds) {
            Map<String, Double> oddMap=prizeMap.get(prizesId);//商品的概率
            Double minNum=oddMap.get(min);
            Double maxNum=oddMap.get(max);
            //校验index在那个商品概率中间
            if(minNum <index && maxNum >= index) {
                prize=tSysAwardsService.selectTSysAwardsById(prizesId);
                break;
            }
        }
        if(prize == null) {
            System.out.println(index);
            prize=new TSysAwards();
        }
        return prize;
    }


}
